//
// Message Controller
//
var ObjectID   = require('mongoose').Types.ObjectId;

module.exports = function(app) {

   // List Messages + Post new Message
   app.route('/messages/list')
      .get(function(req, res){
         //Message.find({}).populate('poster', 'local.email').exec(function(err, msgs){
         Domain.Message.find({}).populate('poster').exec(function(err, msgs){
            if(err) throw err
            res.render('messages/list', {user: req.user, messages: msgs });
         });
      })
      
      .post(app.isLoggedIn, function(req, res){
         var msg        = new Domain.Message();
         msg.title      = req.body.title;
         msg.body       = req.body.body;
         msg.date       = Date.now();
         msg.poster     = req.user;
         msg.save(function(err){
            if(err) throw err
            res.redirect('/messages/list');
         });
      });

   // Edit Message
   app.route('/messages/edit/:id')
      .get(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         Domain.Message.findById(id).exec(function(err, msg){
            if(err) throw err;
            res.render('messages/edit', {message: msg, user: req.user, csrf: req.csrfToken() });
         });
      })

      .post(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         Domain.Message.update({_id: ObjectID(id)}, {
            title : req.body.title,
            body  : req.body.body
         }, function(err, num){
            if(err) throw err;
            res.redirect('/messages/list');
         });
      });

};




